// Breathing Exercise Timer and Animation Controller
let timerInterval = null;
let breathingInterval = null;
let totalSeconds = 300; // 5 minutes default
let remainingSeconds = 300;
let isRunning = false;
let isPaused = false;
let cycleCount = 0;
let currentPhase = 'ready'; // ready, inhale, hold, exhale

const phases = {
  inhale: { duration: 4, next: 'hold' },
  hold: { duration: 7, next: 'exhale' },
  exhale: { duration: 8, next: 'inhale' }
};

// DOM Elements
const timerDisplay = document.getElementById('timerDisplay');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');
const breathingCircle = document.getElementById('breathingCircle');
const breathPhase = document.getElementById('breathPhase');
const cycleCountEl = document.getElementById('cycleCount');
const timeRemainingEl = document.getElementById('timeRemaining');
const closeBtn = document.getElementById('closeBtn');

// Initialize
document.addEventListener('DOMContentLoaded', () => {
  updateTimerDisplay();
  setupEventListeners();
  updateInstructions();
});

function setupEventListeners() {
  startBtn.addEventListener('click', startBreathing);
  pauseBtn.addEventListener('click', pauseBreathing);
  resetBtn.addEventListener('click', resetBreathing);
  closeBtn.addEventListener('click', () => {
    if (isRunning) {
      if (confirm('Are you sure you want to close? The timer will be reset.')) {
        resetBreathing();
        // Try to close, but if it doesn't work (e.g., opened as tab), just reset
        try {
          window.close();
        } catch (e) {
          // Window.close() doesn't work for tabs opened via chrome.tabs.create
          // User can close the tab manually
        }
      }
    } else {
      try {
        window.close();
      } catch (e) {
        // Window.close() doesn't work for tabs opened via chrome.tabs.create
        // User can close the tab manually
      }
    }
  });
}

function startBreathing() {
  if (isPaused) {
    // Resume from pause
    isPaused = false;
    startTimer();
    startBreathingCycle();
  } else {
    // Start fresh
    isRunning = true;
    currentPhase = 'inhale';
    cycleCount = 0;
    startTimer();
    startBreathingCycle();
  }
  
  startBtn.style.display = 'none';
  pauseBtn.style.display = 'inline-block';
}

function pauseBreathing() {
  isPaused = true;
  isRunning = false;
  stopTimer();
  stopBreathingCycle();
  
  startBtn.style.display = 'inline-block';
  pauseBtn.style.display = 'none';
  breathingCircle.className = 'breathing-circle';
  breathPhase.textContent = 'Paused';
}

function resetBreathing() {
  isRunning = false;
  isPaused = false;
  remainingSeconds = totalSeconds;
  cycleCount = 0;
  currentPhase = 'ready';
  
  stopTimer();
  stopBreathingCycle();
  
  updateTimerDisplay();
  updateCycleCount();
  breathingCircle.className = 'breathing-circle';
  breathPhase.textContent = 'Ready';
  updateInstructions();
  
  startBtn.style.display = 'inline-block';
  pauseBtn.style.display = 'none';
}

function startTimer() {
  timerInterval = setInterval(() => {
    if (remainingSeconds > 0) {
      remainingSeconds--;
      updateTimerDisplay();
    } else {
      // Timer finished
      stopTimer();
      stopBreathingCycle();
      breathingCircle.className = 'breathing-circle';
      breathPhase.textContent = 'Complete!';
      alert('Breathing exercise complete! Great job!');
      resetBreathing();
    }
  }, 1000);
}

function stopTimer() {
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
}

function startBreathingCycle() {
  if (!isRunning) return;
  
  performBreathingPhase();
}

function stopBreathingCycle() {
  if (breathingInterval) {
    clearTimeout(breathingInterval);
    breathingInterval = null;
  }
}

function performBreathingPhase() {
  if (!isRunning || remainingSeconds <= 0) return;
  
  const phase = phases[currentPhase];
  if (!phase) return;
  
  // Update UI
  breathingCircle.className = `breathing-circle ${currentPhase}`;
  breathPhase.textContent = getPhaseText(currentPhase);
  updateInstructions();
  
  // Move to next phase after duration
  breathingInterval = setTimeout(() => {
    if (currentPhase === 'exhale') {
      cycleCount++;
      updateCycleCount();
    }
    
    currentPhase = phase.next;
    performBreathingPhase();
  }, phase.duration * 1000);
}

function getPhaseText(phase) {
  const texts = {
    ready: 'Ready',
    inhale: 'Breathe In',
    hold: 'Hold',
    exhale: 'Breathe Out'
  };
  return texts[phase] || 'Ready';
}

function updateTimerDisplay() {
  const minutes = Math.floor(remainingSeconds / 60);
  const seconds = remainingSeconds % 60;
  const display = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  timerDisplay.textContent = display;
  timeRemainingEl.textContent = display;
}

function updateCycleCount() {
  cycleCountEl.textContent = cycleCount;
}

function updateInstructions() {
  // Highlight the relevant instruction step based on current phase
  const steps = document.querySelectorAll('.instruction-step');
  steps.forEach((step, index) => {
    step.classList.remove('active');
  });
  
  // Show relevant instruction based on phase
  if (currentPhase === 'ready') {
    document.getElementById('step1').classList.add('active');
  } else if (currentPhase === 'inhale') {
    document.getElementById('step2').classList.add('active');
  } else if (currentPhase === 'hold') {
    document.getElementById('step3').classList.add('active');
  } else {
    document.getElementById('step4').classList.add('active');
  }
}

// Clean up on page unload
window.addEventListener('beforeunload', () => {
  stopTimer();
  stopBreathingCycle();
});

